package handler

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"starry_sky/internal/core"
	"starry_sky/internal/model"
	"starry_sky/internal/service"
	"starry_sky/internal/service/permission-service"
	"starry_sky/internal/tools/logger"
)

func CreatePermission(c *gin.Context) {
	var permission model.Permission
	err := c.ShouldBindJSON(&permission)
	if logger.HasError(err) {
		c.JSON(http.StatusInternalServerError, core.NewError(core.BAD_REQUEST, "接受参数错误"))
		return
	}
	err = permission_service.CreatePermission(&permission)
	if err != nil {
		c.JSON(http.StatusInternalServerError, core.NewError(core.INTERNAL_SERVER_ERROR, "权限新增失败"))
		return
	}
	c.JSON(http.StatusOK, core.OK.WithData(permission.ID))
}

func UpdatePermission(c *gin.Context) {
	var permission model.Permission
	err := c.ShouldBindJSON(&permission)
	if logger.HasError(err) {
		c.JSON(http.StatusInternalServerError, core.NewError(core.BAD_REQUEST, "接受参数错误"))
		return
	}
	err = permission_service.UpdatePermission(&permission)
	if err != nil {
		c.JSON(http.StatusInternalServerError, core.NewError(core.INTERNAL_SERVER_ERROR, "权限更新失败"))
		return
	}
	c.JSON(http.StatusOK, core.OK.WithData(true))
}

func DeletePermission(c *gin.Context) {
	var permission model.Permission
	err := c.ShouldBindJSON(&permission)
	if logger.HasError(err) {
		c.JSON(http.StatusInternalServerError, core.NewError(core.BAD_REQUEST, "接受参数错误"))
		return
	}
	err = permission_service.DeletePermission(&permission)
	if err != nil {
		c.JSON(http.StatusInternalServerError, core.NewError(core.INTERNAL_SERVER_ERROR, "权限删除失败"))
		return
	}
	c.JSON(http.StatusOK, core.OK.WithData(true))
}

func FindPermissionById(c *gin.Context) {
	id := c.Query("id")
	if id == "" {
		c.JSON(http.StatusInternalServerError, core.NewError(core.BAD_REQUEST, "接受参数错误"))
		return
	}
	var permission model.Permission
	permission.ID = id
	err := service.FindById(&permission)
	if err != nil {
		c.JSON(http.StatusInternalServerError, core.NewError(core.INTERNAL_SERVER_ERROR, "权限查询失败"))
		return
	}
	c.JSON(http.StatusOK, core.OK.WithData(permission))
}

func FindAllPermission(c *gin.Context) {
	var allPermission []model.Permission
	err := service.FindAll(&allPermission)
	if err != nil {
		c.JSON(http.StatusInternalServerError, core.NewError(core.INTERNAL_SERVER_ERROR, "权限查询失败"))
		return
	}
	c.JSON(http.StatusOK, core.OK.WithData(allPermission))
}
